var express = require('express');
var router = express.Router();

const fetch = require('node-fetch');

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});


router.get('/data', function (req, res, next) {
  //if (req.query.p1 == '1')
    //res.send('123好的');
  //else
    //res.send('nodata');
    var json01 = {
    'name': '123',
    'id': '222'
  }
  res.send(json01);
});


//json
router.get('/json', function (req, res, next) {
  var json01 = {
    'name': '123',
    'id': '222'
  }
  res.send(json01);
});


//moon1
router.get('/moon1', async (req, res, next) => {
  if (req.query.key != 'coolmoonsun') {
    res.send('no key')
    return
  }

  const url = 'https://api.ipgeolocation.io/astronomy?apiKey=0569304ad242422ba48af58f83504cf8&lat=' + req.query.lat + '&long=' + req.query.long

  try {
    const response = await fetch(url);

    // 检查请求是否成功
    if (!response.ok) {
      throw new Error(`Failed to fetch data with status: ${response.status}`);
    }

    // 将响应体解析为JSON格式的数据
    const data = await response.json();

    res.send(data);
  } catch (error) {
    console.error('Error fetching external data:', error);
    res.status(500).send({ error: 'An error occurred while fetching the data.' });
  }

});


//moon2
router.get('/moon2', async (req, res, next) => {
  if (req.query.key != 'coolmoonsun') {
    res.send('no key')
    return
  }

  // debug
  //let jsonTemp = { "status": 0, "result": { "location": { "lon": 113.383611, "lat": 23.132778 }, "moon": [{ "date": "2024-03-18", "moonrise": "12:35:36", "moonset": "01:55:12", "phaseAngle": 83.97, "percent": 55.25, "phase": "WaxingGibbous", "phaseCn": "盈凸月", "phaseCode": 8 }, { "date": "2024-03-19", "moonrise": "13:32:29", "moonset": "02:47:24", "phaseAngle": 72.5, "percent": 65.04, "phase": "WaxingGibbous", "phaseCn": "盈凸月", "phaseCode": 7 }, { "date": "2024-03-20", "moonrise": "14:28:42", "moonset": "03:33:25", "phaseAngle": 61.3, "percent": 74.01, "phase": "WaxingGibbous", "phaseCn": "盈凸月", "phaseCode": 6 }], "full": [], "new": [] } }
  //res.send(jsonTemp)
  //return

  const url = 'https://eolink.o.apispace.com/3244/lives_geo/v001/moon?days=' + req.query.days + '&lonlat=' + req.query.lonlat
  const headers = {
    // 'Content-Type': 'application/json',
    'X-APISpace-Token': 'm02tvowmv87ocwvi8zq2nrhhthkvsu1g',
  };

  try {
    const response = await fetch(url, { method: 'GET', headers });

    if (!response.ok) {
      throw new Error(`Failed to fetch data with status: ${response.status}`);
    }

    // 解析为JSON
    const data = await response.json();

    res.send(data);
  } catch (error) {
    console.error('Error fetching external data:', error);
    res.status(500).send({ error: 'An error occurred while fetching the data.' });
  }

});


//sun
router.get('/sun', async (req, res, next) => {
  if (req.query.key != 'coolmoonsun') {
    res.send('no key')
    return
  }

  // debug
  //let jsonTemp = { "location": { "latitude": 23.132778, "longitude": 113.383611 }, "date": "2024-03-18", "current_time": "21:47:26.224", "sunrise": "06:32", "sunset": "18:36", "sun_status": "-", "solar_noon": "12:34", "day_length": "12:04", "sun_altitude": -43.65928289646663, "sun_distance": 148823057.2793147, "sun_azimuth": 293.0583532022276, "moonrise": "12:34", "moonset": "01:56", "moon_status": "-", "moon_altitude": 62.433150602753656, "moon_distance": 395418.83892895794, "moon_azimuth": 286.2219944294866, "moon_parallactic_angle": 92.97251921038053 }
  //res.send(jsonTemp)
  //return


  const url = 'https://api.ipgeolocation.io/astronomy?apiKey=0569304ad242422ba48af58f83504cf8&lat=' + req.query.lat + '&long=' + req.query.long;


  try {
    const response = await fetch(url);

    if (!response.ok) {
      throw new Error(`Failed to fetch data with status: ${response.status}`);
    }

    // 解析为JSON
    const data = await response.json();

    res.send(data);
  } catch (error) {
    console.error('Error fetching external data:', error);
    res.status(500).send({ error: 'An error occurred while fetching the data.' });
  }

});


//location
router.get('/location', async (req, res, next) => {
  if (req.query.key != 'coolmoonsun') {
    res.send('no key');
    return;
  }


  // debug
  // let jsonTemp = { "ip": "119.130.161.101", "city": "Guangzhou", "latitude": "23.12897", "longitude": "113.26683" }
  // res.send(jsonTemp)
  // return


  const urlLocation = 'https://api.ipgeolocation.io/ipgeo?apiKey=0569304ad242422ba48af58f83504cf8&ip=' + req.query.ip + '&fields=city,latitude,longitude&lang=cn';

  try {
    const response = await fetch(urlLocation);

    if (!response.ok) {
      throw new Error(`Failed to fetch data with status: ${response.status}`);
    }

    // 解析为JSON
    const dataLocation = await response.json();


    // dataLocation.city = '广州test';

    // res.send(dataLocation);
    // return;


    // //获取城市名称
    // const urlCity = 'http://ip-api.com/json/' + req.query.ip + '?lang=zh-CN';

    // try {
    //   const responseCity = await fetch(urlCity);

    //   if (!responseCity.ok) {
    //     throw new Error(`Failed to fetch data with status: ${response.status}`);
    //   }

    //   // 解析为JSON
    //   const dataCity = await responseCity.json();

    //   dataLocation.city = dataCity.city;

    //   res.send(dataLocation);

    // } catch (error) {
    //   console.error('Error fetching external data:', error);
    //   res.status(500).send({ error: 'An error occurred while fetching the data.' });
    // }


    //获取城市名称
    const urlCity = 'https://www.ip.cn/api/index?ip=' + req.query.ip + '&type=1';

    try {
      const responseCity = await fetch(urlCity);

      if (!responseCity.ok) {
        throw new Error(`Failed to fetch data with status: ${response.status}`);
      }

      // 解析为JSON
      const dataCity = await responseCity.json();

      let address = dataCity.address;
      let stringArray = address.split(' ');
      dataLocation.city = stringArray[stringArray.length - 2];
      if (dataLocation.city.length == 0)
        dataLocation.city = stringArray[stringArray.length - 3];

      res.send(dataLocation);

    } catch (error) {
      console.error('Error fetching external data:', error);
      res.status(500).send({ error: 'An error occurred while fetching the data.' });
    }
  } catch (error) {
    console.error('Error fetching external data:', error);
    res.status(500).send({ error: 'An error occurred while fetching the data.' });
  }

});


//solareclipse
router.get('/solareclipse', async (req, res, next) => {
  if (req.query.key != 'coolmoonsun') {
    res.send('no key')
    return
  }

  let solarEclipseData = {
    city: '阿肯色州',
    date: '2024-04-08',
    begin: '12:31:17',
    end: '15:09:51',
    totalBegin: '13:49:43',
    totalEnd: '13:51:47',
    localTime: {
      date: '2024-04-09',
      begin: '01:31:17',
      end: '04:09:51',
      totalBegin: '02:49:43',
      totalEnd: '02:51:47',
    },
    updateDate: '',
    ready: true
  };

  let curDate = new Date();

  var YMD = `${curDate.getFullYear()}-${(curDate.getMonth() + 1).toString().padStart(2, '0')}-${curDate.getDate().toString().padStart(2, '0')}`;

  solarEclipseData.updateDate = YMD;

  res.send(solarEclipseData);

});

module.exports = router;
